import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutterdemo/dao/home_dao.dart';
import 'package:flutterdemo/model/common_model.dart';
import 'package:flutterdemo/model/config_model.dart';
import 'package:flutterdemo/model/grid_nav_model.dart';
import 'package:flutterdemo/model/home_model.dart';
import 'package:flutterdemo/model/sales_box_model.dart';
import 'package:flutterdemo/pages/search_page.dart';
import 'package:flutterdemo/pages/speak_page.dart';
import 'package:flutterdemo/widget/grid_nav.dart';
import 'package:flutterdemo/widget/local_nav.dart';
import 'package:flutterdemo/widget/sales_box.dart';
import 'package:flutterdemo/widget/search_bar.dart';
import 'package:flutterdemo/widget/sub_nav.dart';
import 'package:flutterdemo/widget/loading_container.dart';
import 'package:flutterdemo/widget/webview.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../util/navigator_util.dart';
import 'dart:convert';

const APPBAR_SCROLL_OFFSET = 100;
const SEARCH_BAR_DEFAULT_TEXT = '网红打卡地 景点 酒店 美食';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  static ConfigModel? configModel;

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List _imageUrls = [
    'https://www.devio.org/io/flutter_app/img/banner/100h10000000q7ght9352.jpg',
    'https://dimg04.c-ctrip.com/images/300h0u000000j05rnD96B_C_500_280.jpg',
    'http://pages.ctrip.com/hotel/201811/jdsc_640es_tab1.jpg',
    'https://dimg03.c-ctrip.com/images/fd/tg/g1/M03/7E/19/CghzfVWw6OaACaJXABqNWv6ecpw824_C_500_280_Q90.jpg'
  ];

  double appBarAlpha = 0;
  String resultString = "";
  List<CommonModel> localNavList = [];
  List<CommonModel> bannerList = [];
  List<CommonModel> subNavList = [];

  //问题2
  GridNavModel? gridNavModel;
  SalesBoxModel? salesBoxModel;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    loadData();
  }

  _onScroll(offset) {
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
    print(appBarAlpha);
  }

  Future<Null> loadData() async {
    //两种方法验证请求到的数据
    // HomeDao.fetch().then((result) {
    //   setState(() {
    //     resultString = json.encode(result);
    //   });
    // }).catchError((e) {
    //   setState(() {
    //     resultString = e.toString();
    //   });
    // });
    try {
      HomeModel model = await HomeDao.fetch();
      setState(() {
        HomePage.configModel = model.configModel;
        localNavList = model.localNavList;
        subNavList = model.subNavList;
        gridNavModel = model.gridNavModel;
        salesBoxModel = model.salesBoxModel;
        bannerList = model.bannerList;
        _loading = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xfff2f2f2),
      body: LoadingContainer(
        isLoading: _loading,
        child: Stack(
          children: <Widget>[
            MediaQuery.removePadding(
              removeTop: true,
              context: context,
              child: RefreshIndicator(
                onRefresh: loadData,
                child: NotificationListener(
                  onNotification: (scrollNotification) {
                    if (scrollNotification is ScrollUpdateNotification &&
                        scrollNotification.depth == 0) {
                      //当第0个元素的时候 才能触发滚动
                      //滚动且是列表滚动的时候
                      _onScroll(scrollNotification.metrics.pixels);
                    }
                    return false;
                  },
                  child: ListView(
                    children: <Widget>[
                      //banner轮播图部分
                      Container(
                        height: 160,
                        child: Swiper(
                          itemCount: bannerList.length,
                          // itemCount: _imageUrls.length,
                          autoplay: true,
                          itemBuilder: (BuildContext context, int index) {
                            return GestureDetector(
                              onTap: () {
                                CommonModel model = bannerList[index];
                                NavigatorUtil.push(
                                    context,
                                    HiWebView(
                                        url: model.url,
                                        title: model.title,
                                        hideAppBar: model.hideAppBar));
                              },
                              child: Image.network(
                                bannerList[index].icon!,
                                // _imageUrls[index],
                                fit: BoxFit.fill,
                              ),
                            );
                          },
                          pagination: SwiperPagination(),
                        ),
                      ),
                      //攻略景点等小圆球布局
                      Padding(
                        padding: const EdgeInsets.fromLTRB(7, 4, 7, 4),
                        child: LocalNav(localNavList: localNavList),
                      ),
                      //问题2 初始化
                      //网格卡片布局
                      if (gridNavModel != null)
                        Padding(
                          padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                          child: GridNav(gridNavModel: gridNavModel!),
                        ),
                      //黄标小活动按钮布局
                      Padding(
                        padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                        child: SubNav(subNavList: subNavList),
                      ),
                      //底部热门活动布局
                      if (salesBoxModel != null)
                        Padding(
                          padding: const EdgeInsets.fromLTRB(7, 0, 7, 4),
                          child: SalesBox(salesBoxModel: salesBoxModel!),
                        ),
                      Container(
                        height: 800,
                        child: ListTile(
                          title: Text(resultString),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
            //头布局
            _appBar
            // Opacity(
            //   //问题一
            //   opacity[[əʊˈpæsəti]] 不透明性: appBarAlpha,
            //   child: Container(
            //     height: 60,
            //     decoration: BoxDecoration(color: Colors.white),
            //     child: Center(
            //       child: Padding(
            //         padding: EdgeInsets.only(top: 20),
            //         child: Text('首页'),
            //       ),
            //     ),
            //   ),
            // )
          ],
        ),
      ),
    );
  }

  Widget get _appBar {
    return Column(
      children: <Widget>[
        Container(
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              //设置AppBar渐变的遮盖背景
              colors: [Color(0x66000000), Colors.transparent],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Container(
            padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
              color: Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255),
            ),
            child: SearchBar(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: SEARCH_BAR_DEFAULT_TEXT,
              leftButtonClick: () {},
            ),
          ),
        ),
        Container(
            height: appBarAlpha > 0.2 ? 0.5 : 0,
            decoration: const BoxDecoration(
                boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]))
      ],
    );
  }

  _jumpToSearch() {
    NavigatorUtil.push(
        context,
        const SearchPage(
          hint: SEARCH_BAR_DEFAULT_TEXT,
        ));
  }

  _jumpToSpeak() {
    NavigatorUtil.push(context, SpeakPage());
  }
}
